<template>
  <div>

    <div class="search-condition">
      <div>
        <span class="name">当前油站：</span>
        <span>{{currentGasStation}}</span>
        <!-- <el-select v-model="oisName" placeholder="请选择油站" style="width: 650px">
          <el-option
            v-for="(item, index) in options"
            :key="index"
            :label="item.gasName"
            :value="item.gasId">
          </el-option>
        </el-select> -->
      </div>
      <!-- <el-button type="primary" size="medium" @click="refresh">查询</el-button> -->
    </div>

    <div class="table-wrap">
      <mer-table :loading="tableLoading"
        :tableConfig="tableConfig"
        :tableData="tableData"
        :pagination="pagination"
        @SizeChange="handleSizeChange"
        @PageChange="pageChange"
        :hasIndex="true"
        :border="false">
        <template slot="effectiveTime" slot-scope="{row}">
          <span v-show="row.status === 1">{{ row.effectiveTime ? row.effectiveTime : '已生效' }}</span>
        </template>
        <template slot="handler" slot-scope="{row}">
          <div>
            <el-button v-show="row.status === 1" class="table-mini-btn" @click="modifyPrice(row)">修改</el-button>
            <el-button class="table-mini-btn" @click="changeRecord(row)">变更记录</el-button>
          </div>
        </template>
      </mer-table>
    </div>

    <!-- 变更记录 -->
    <el-dialog :visible.sync="changeRecordVisible" center>
      <div slot="title" class="dialog-title">油价变更记录</div>
      <el-table :data="changeRecordData" stripe style="width: 100%" size="small" v-loading="recordTableLoading">
        <el-table-column property="createUser" label="操作人" align="center"></el-table-column>
        <el-table-column property="createDt" label="操作时间" align="center"></el-table-column>
        <el-table-column property="operate" label="操作类型" align="center" width="100"></el-table-column>
        <el-table-column property="operateRecord" label="操作记录" align="center" width="250">
          <template slot-scope="{row}">
            <!-- <div>
              {{ `枪价：由${row.beforePriceGun}元 改为：${row.afterPriceGun}元` }}
            </div> -->
            <span>{{ row.record }}</span>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeRecordVisible = false">返回</el-button>
      </span>
    </el-dialog>

    <!-- 修改油价 -->
    <el-dialog :visible.sync="modifyOilGunVisible" center width="600px">
      <div slot="title" class="dialog-title">修改油价</div>
      <el-form :model="modifyData" label-width="140px" :rules="formRules" ref="form">
        <el-form-item label="油号：">
          <el-input v-model="modifyData.oilNum" disabled></el-input>
        </el-form-item>
        <el-form-item label="单位：">
          <el-input v-model="modifyData.unitName" disabled></el-input>
        </el-form-item>
        <!-- 船舶显示表单 -->
        <template v-if="isShipStation">
          <el-form-item label="当前枪价：">
            <el-input v-model="modifyData.priceGun" disabled></el-input>
          </el-form-item>
          <el-form-item label="当前无票枪价：">
            <el-input v-model="modifyData.priceGunNoInvoice" disabled></el-input>
          </el-form-item>
          <el-form-item label="调整后枪价：" prop="modifyPrice">
            <el-input-number v-model="modifyData.modifyPrice" :precision="2" :max="9000"></el-input-number>
          </el-form-item>
          <el-form-item label="调整后无票枪价：" prop="updatePriceGunNoInvoice">
            <el-input-number v-model="modifyData.updatePriceGunNoInvoice" :precision="2" :max="9000"></el-input-number>
          </el-form-item>
        </template>
        <!-- 油站显示表单 -->
        <template v-else>
          <el-form-item label="国际价：">
            <el-input v-model="modifyData.priceOfficial" disabled></el-input>
          </el-form-item>
          <el-form-item label="当前枪价：">
            <el-input v-model="modifyData.priceGun" disabled></el-input>
          </el-form-item>
          <el-form-item label="调整后枪价：" prop="modifyPrice">
            <el-input-number v-model="modifyData.modifyPrice" :precision="2" :max="9000"></el-input-number>
          </el-form-item>
          <!-- 金盾权限展示 -->
          <template v-if="hasGoldenRight">
            <el-form-item label="团油价（商用车）" prop="merchantPrice">
              <el-input v-model="modifyData.merchantPrice"></el-input>
            </el-form-item>
            <el-form-item label="团油价（私家车）" prop="noMerchantPrice">
              <el-input v-model="modifyData.noMerchantPrice"></el-input>
            </el-form-item>
          </template>
        </template>
        <el-form-item label="生效时间：" prop="entryIntoForceTime">
          <el-radio :label="0" v-model="timeType">立即</el-radio>
          <div>
            <el-radio :label="1" v-model="timeType">指定日期</el-radio>
            <el-date-picker
              v-model="modifyData.entryIntoForceTime"
              align="right"
              type="datetime"
              :disabled="!Boolean(timeType)"
              placeholder="选择日期"
              :pickerOptions="pickerOptions">
            </el-date-picker>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyOilGunVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submit">提交</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import listPage from '@/mixins/listPage'
import { getGasPriceList, updateOilPrice, checkLog, getAllGasInfoList } from '@/api/gasStationManage/gasInfo'
import { getGoldenRight } from '@/api/common'
import dayjs from 'dayjs'
import { mapState } from 'vuex'

const TABLECONFIG = [
  // {label: '油站编码', prop: 'gasId', width: '60'},
  // {label: '油站名称', prop: 'gasName'},
  {label: '油号', prop: 'oilNum', width: 30},
  {label: '单位', prop: 'unitName', width: 30},
  {label: '国标价', prop: 'priceOfficial', width: 30},
  {label: '枪价', prop: 'priceGun', width: 30},
  {label: '当前枪价', prop: 'priceGun', width: 50},
  {label: '变更后枪价', prop: 'updateGunPrice', width: 50},
  {label: '生效时间', prop: 'effectiveTime',slot: 'effectiveTime', width: 80},
  {label: '状态', prop: 'statusName', width: 30},
  {label: '操作项', prop: 'tradingTime', slot: 'handler', width: 80}
]

// 金盾权限额外字段
const TABLE_ELSE = [
  {label: '团油价(商用车)', prop: 'merchantPrice', width: 50},
  {label: '团油价(私家车)', prop: 'noMerchantPrice', width: 50}
]

const SHIPTABLECONFIG = [
  {label: '油号', prop: 'oilNum', width: 30},
  {label: '单位', prop: 'unitName', width: 30},
  {label: '国标价', prop: 'priceOfficial', width: 30},
  {label: '当前枪价', prop: 'priceGun', width: 50},
  {label: '当前无票枪价', prop: 'priceGunNoInvoice', width: 50},
  {label: '变更后枪价', prop: 'updateGunPrice', width: 50},
  {label: '变更后无票枪价', prop: 'updatePriceGunNoInvoice', width: 50},
  {label: '生效时间', prop: 'effectiveTime',slot: 'effectiveTime', width: 80},
  {label: '状态', prop: 'statusName', width: 30},
  {label: '操作项', prop: 'tradingTime', slot: 'handler', width: 80}
]

export default {
  name: 'gasStationManage_oilPriceManage',
  mixins: [listPage],
  data () {
    let checkTime = (rule, value, callback) => {
      if (this.timeType === 1) {
        if(!value){
          callback(new Error('请选择时间'))
        }
        callback() 
      }else{
        callback()
      }
    }
    return {
      options: [],
      oisName: '',
      tableConfig: [],
      tableLoading: false,
      recordTableLoading: false,
      tableData: {
        total: 0,
        records: []
      },
      pagination: { pageIndex: 1, pageSize: 10 },
      changeRecordVisible: false,
      modifyOilGunVisible: false,
      changeRecordData: [],
      statusList: ['关闭', '开启'],
      modifyData: {
        oilNo: '',
        unitName: '',
        priceOfficial: '',
        priceGun: '',
        entryIntoForceTime: '',
        modifyPrice: '',
        merchantPrice: '',
        noMerchantPrice: '',
        updatePriceGunNoInvoice: '',
        priceGunNoInvoice: ''
      },
      timeType: 0,
      formRules: {
        modifyPrice: [
          { required: true, message: '请输入枪价', trigger: 'blur' }
        ],
        entryIntoForceTime:[
          { validator:checkTime, trigger: 'blur' }
        ],
        merchantPrice: [
          { required: true, message: '请输入团油价（商用车）', trigger: 'blur' }
        ],
        noMerchantPrice: [
          { required: true, message: '请输入团油价（私家车）', trigger: 'blur' }
        ],
        priceGunNoInvoice: [
          { required: true, message: '请输入无票枪价', trigger: 'blur' }
        ],
        updatePriceGunNoInvoice: [
          { required: true, message: '请输入调整后无票枪价', trigger: 'blur' }
        ]
      },
      currentGasStation:'',
      submitLoading: false,
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < (Date.now()-24*60*60*1000)
        }
      },
      hasGoldenRight: false, // 是否有金盾权限
      gasId: '',
      pontoonGasIds: [], // 船舶ID的list
      isShipStation: false, // 是否为船舶加油
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
  },
  methods: {
    async refresh () {
      this.tableLoading = true
      try {
        const { code, result = [], totalRow } = await getGasPriceList(this.pagination)
        if (code !== 200) return
        this.tableData.records = result
        this.tableData.total = totalRow
      } catch (err) {
        console.log(err)
      } finally {
        this.tableLoading = false
      }
    },
    // 初始化油站名称下拉框
    async initSelectOptions () {
      try {
        const { code, result = [] } = await getAllGasInfoList()
        if (code !== 200) return
        this.currentGasStation = result.length ? result[0].gasName : ''
        this.gasId = result.length ? result[0].gasId : ''
        this.whetherHasShip()
      } catch (err) {
        console.log(err)
      }
    },
    // 判断查询油站是否是船舶油站
    whetherHasShip () {
      this.isShipStation = this.pontoonGasIds.includes(this.gasId)
      this.tableConfig = this.isShipStation ? SHIPTABLECONFIG : TABLECONFIG
    },
    submit () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.submitLoading = true
          let params = {
            gasId: this.modifyData.gasId,
            priceGun: this.modifyData.modifyPrice,
            oilNo: this.modifyData.oilNo,
            effctiveTime: !this.timeType ? '' : dayjs(this.modifyData.entryIntoForceTime).format('YYYY-MM-DD HH:mm:ss'),
            merchantPrice: this.modifyData.merchantPrice,
            noMerchantPrice: this.modifyData.noMerchantPrice
          }
          
          // 船舶参数需要增加 updatePriceGunNoInvoice
          if(this.isShipStation) params.priceGunNoInvoice = this.modifyData.updatePriceGunNoInvoice
          
          try {
            const {code, result} = await updateOilPrice(params)
            if (code !== 200) return
            if (result) {
              this.$message.success('修改成功')
              this.modifyOilGunVisible = false
              this.refresh() 
            } else {
              this.$message.error('修改失败')
            }
          } catch (err) {
            console.log(err)
          } finally{
            this.submitLoading = false
          }
        }
      })
    },
    // 修改
    modifyPrice (row) {
      this.timeType = 0
      // this.modifyData.modifyPrice = ''
      this.modifyData.entryIntoForceTime = ''
      this.modifyData.merchantPrice = ''
      this.modifyData.noMerchantPrice = ''
      this.modifyOilGunVisible = true
      Object.assign(this.modifyData, row)
      this.modifyData.updatePriceGunNoInvoice = ''
      this.modifyData.modifyPrice = row.priceGun
    }
    ,
    // 变更记录
    async changeRecord (row) {
      this.changeRecordVisible = true
      this.recordTableLoading = true
      try {
        const {code, result} = await checkLog({gasId: row.gasId, oilNo: row.oilNo})
        if (code !== 200) return
        this.changeRecordData = result
      } catch (err) {
        console.log(err)
      } finally {
        this.recordTableLoading = false
      }
    },
    async getGoldenRight () {
      try {
        const { code, result } = await getGoldenRight()
        if (code !== 200) return
        this.hasGoldenRight = result
        if (result) {
          const index = this.tableConfig.findIndex(item => item.prop === 'updateGunPrice')
          this.tableConfig.splice(index, 0, ...TABLE_ELSE)
        }
      } catch (error) {
        console.log(error)
      }
    }
  },
  created () {
    this.pontoonGasIds = this.userInfo.pontoonGasIds || []
    this.refresh()
    this.initSelectOptions()
    this.getGoldenRight()
  }
}
</script>
<style lang="less" scoped>
  @import url('../mixin.less');
</style>